import React from "react"
import { Image, ScrollView, View } from "@tarojs/components"
import { Search, DropdownMenu, Cell, Sticky } from "@taroify/core"
import { Success } from "@taroify/icons"
import GpContainer from "@/components/GpContainer"
import { setPageMeta } from "@/utils/common"
import Taro, { pxTransform } from "@tarojs/taro"
import GpMustReadItem from "@/components/GpMustReadItem"
import GpJumpNavs from "@/components/GpJumpNavs"
import GpCurrentPort from "@/components/GpCurrentPort"
import clsx from "clsx"
import GpTabbar from "@/components/GpTabbar"
import GpEmpty from "@/components/GpEmpty"
import GpScrollLoading from "@/components/GpScrollLoading"
import { getExamList, getNewsColumnDetail } from "@/apis/index"
import { PagePath } from "@/constants/pageMap"
import { navigation } from "@/utils/router"
import styles from "@/styles/common/top-fixed.module.scss"
import myStyles from "./index.module.scss"

const iconSize = pxTransform(20)
const firstCategoryAllValue = "000000"
const non_lastCategoryAllValue = "-9999"
type IAreaMap = ICascadeMap<IDropDownFilterOption<string>[], string>
type IState = {
  /** 过滤面板所选择的过滤项 */
  selectedFilterKey: any
  yearOptions: IDropDownFilterOption<number>[]
  selectedYear?: number
  /** 所在地区列表 一级*/
  areaOptions: IDropDownFilterOption<string>[]
  /** 所在地区列表 二级*/
  lastAreaOptions: IDropDownFilterOption<string>[]
  /** 选择的地区第一层 */
  selectedAreaFirstCate?: string
  /** 选择的地区第二层 */
  selectedAreaLastCate?: string
  categoryOptions: IDropDownFilterOption<number>[]
  selectedCategory?: number
  keyword: string
  pagination: IPagination
  list: any[]
  showLoading: boolean
  picture?: string
  navigationTitle: string
}
type IData = {
  areaMap: IAreaMap
  /** 查询参数 栏目id */
  columnId?: number
  pageMeta: {
    province?: string
    category?: string
    year?: string
    pageLoaded: boolean
  }
  seoTemplate?: {
    keywords: string
    description: string
    title: string
  }
}
class ColumnDetail extends React.Component<unknown, IState> {
  extData: IData
  constructor(props) {
    super(props)
    this.state = {
      selectedFilterKey: false,
      yearOptions: [],
      areaOptions: [],
      lastAreaOptions: [],
      categoryOptions: [],
      keyword: "",
      pagination: {
        page: 1,
        pageCount: 1
      },
      list: [],
      showLoading: true
    }
    this.extData = {
      areaMap: {},
      pageMeta: {
        pageLoaded: false
      }
    }
  }
  onShareAppMessage() {}
  collectQuery = (options: Recordable) => {
    this.extData.columnId = Number(options.id)
  }
  onLoad(options: Recordable) {
    this.collectQuery(options)
    this.getDropdownFilters().then(() => {
      this.search(1)
    })
  }
  componentDidShow() {
    this.setPageInfo()
  }
  setPageInfo() {
    const { pageLoaded, province, category, year } = this.extData.pageMeta
    if (pageLoaded && this.extData.seoTemplate) {
      const { title, description, keywords } = this.extData.seoTemplate
      setPageMeta({
        title: title
          .replace("[地区]", province as string)
          .replace("[年份]", year as string)
          .replace("[培训项目]", category as string),
        description: description
          .replace("[地区]", province as string)
          .replace("[年份]", year as string)
          .replace("[培训项目]", category as string),
        keywords: keywords
          .replace("[地区]", province as string)
          .replace("[年份]", year as string)
          .replace("[培训项目]", category as string)
      })
    }
  }
  getPageInfo = (params: any) => {
    const { areaOptions, lastAreaOptions, categoryOptions, yearOptions } = this.state
    if (!params.province) {
      // 不限
      this.extData.pageMeta.province = "全国"
    } else {
      if (params.city) {
        const current = lastAreaOptions.find(l => l.value === params.city)
        this.extData.pageMeta.province = current?.text as string
      } else {
        const current = areaOptions.find(l => l.value === params.province)
        this.extData.pageMeta.province = current?.text as string
      }
    }
    if (!params.projectId) {
      this.extData.pageMeta.category = ""
    } else {
      const current = categoryOptions.find(l => l.value === params.projectId)
      this.extData.pageMeta.category = current?.text as string
    }
    if (!params.year) {
      this.extData.pageMeta.year = ""
    } else {
      const current = yearOptions.find(l => l.value === params.year)
      this.extData.pageMeta.year = current?.text as string
    }
    this.extData.pageMeta.pageLoaded = true
    this.setPageInfo()
  }
  getDropdownFilters = () => {
    const { columnId } = this.extData
    return new Promise(resolve => {
      getNewsColumnDetail({ columnId: columnId as number }).then(res => {
        if (res.data.success) {
          const retData = res.data.data
          const yearOptions: IDropDownFilterOption<number>[] = (retData.year || []).map(l => ({
            value: l.value,
            text: l.label
          }))
          const areaMap: IAreaMap = {}
          const areaOptions: IDropDownFilterOption<string>[] = (retData.areas || []).map(l => {
            const childs = (l.childs || []).map(child => ({
              value: child.value,
              text: child.label
            }))
            areaMap[l.value] = childs
            return {
              value: l.value,
              text: l.label
            }
          })
          this.extData.areaMap = areaMap
          const lastAreaOptions = areaMap[this.state.selectedAreaFirstCate as string] || []
          const categoryOptions: IDropDownFilterOption<number>[] = (retData.categorys || []).map(
            l => ({
              value: l.value,
              text: l.label
            })
          )
          this.setState(
            {
              yearOptions,
              areaOptions,
              lastAreaOptions,
              categoryOptions,
              picture: retData.picture,
              navigationTitle: retData.name
            },
            () => {
              resolve(null)
            }
          )
          this.extData.seoTemplate = retData.seo
          Taro.setNavigationBarTitle({
            title: retData.name
          })
        }
      })
    })
  }
  search = (page = 1, showLoading = true) => {
    if (showLoading) {
      Taro.showLoading()
    }
    const { selectedYear, keyword, selectedAreaFirstCate, selectedAreaLastCate, selectedCategory } =
      this.state
    const params = {
      columnId: this.extData.columnId as number
    } as IApiRelative.IGetExamList.IParams["search"]
    const metaObj = {} as any
    if (selectedYear) {
      params.year = selectedYear
      metaObj.year = selectedYear
    }
    if (keyword) {
      params.keyword = keyword
    }
    if (selectedCategory) {
      params.projectId = selectedCategory
      metaObj.projectId = selectedCategory
    }
    if (selectedAreaFirstCate !== firstCategoryAllValue) {
      params.areaId = selectedAreaFirstCate
      metaObj.province = selectedAreaFirstCate
      if (selectedAreaLastCate && selectedAreaLastCate !== non_lastCategoryAllValue) {
        params.areaId = selectedAreaLastCate
        metaObj.city = selectedAreaLastCate
      }
    } else {
      // 不限
      // if (selectedAreaLastCate && selectedAreaLastCate !== non_lastCategoryAllValue) {
      //   params.city = selectedAreaLastCate
      // }
    }
    this.getPageInfo(metaObj)
    return getExamList({
      search: params,
      pagination: {
        current: page,
        pageSize: 10
      }
    })
      .then(res => {
        if (res.data.success) {
          const retData = res.data.data
          const retList = retData.list || []
          if (page === 1) {
            this.setState({
              list: retList
            })
          } else {
            this.setState({
              list: this.state.list.concat(retList)
            })
          }
          this.setState({
            pagination: {
              page: retData.pagination.current,
              pageCount: retData.pagination.pageCount
            },
            showLoading: retData.pagination.current + 1 <= retData.pagination.pageCount
          })
        }
      })
      .finally(() => {
        if (showLoading) {
          Taro.hideLoading()
        }
      })
  }
  onPullDownRefresh() {
    this.search(1, false).finally(() => {
      Taro.stopPullDownRefresh()
    })
  }
  onReachBottom() {
    const { pagination } = this.state
    if (pagination.page + 1 <= pagination.pageCount) {
      this.search(pagination.page + 1, false)
    }
  }
  handleDropdownMenuChange = (filterKey: any) => {
    this.setState({
      selectedFilterKey: filterKey
    })
  }
  handleClickYear = (item: IDropDownFilterOption) => {
    this.setState(
      {
        selectedYear: item.value
      },
      () => this.search(1)
    )
    this.handleDropdownMenuChange(false)
  }
  handleClickCategory = (item: IDropDownFilterOption) => {
    this.setState(
      {
        selectedCategory: item.value
      },
      () => this.search(1)
    )
    this.handleDropdownMenuChange(false)
  }
  /** 快捷导航 */
  renderJumpNavs = () => {
    return (
      <View className="bg-white ">
        {/* mt-20px */}
        <GpJumpNavs />
      </View>
    )
  }
  handleKeywordChange = (ev: any) => {
    this.setState({
      keyword: ev.detail.value
    })
  }
  handleClickAreaLastCate = (item: IDropDownFilterOption<string>) => {
    this.setState(
      {
        selectedAreaLastCate: item.value
      },
      () => {
        this.search(1)
      }
    )
    this.handleDropdownMenuChange(false)
  }
  handleClickAreaFirstCate = (item: IDropDownFilterOption<string>) => {
    console.log("handleClickLevel----", item, this.extData.areaMap)
    if (item.value !== firstCategoryAllValue) {
      this.setState({
        selectedAreaFirstCate: item.value,
        lastAreaOptions: this.extData.areaMap[item.value],
        selectedAreaLastCate: non_lastCategoryAllValue
      })
    } else {
      // 不限
      this.setState(
        {
          selectedAreaFirstCate: firstCategoryAllValue,
          lastAreaOptions: [],
          selectedAreaLastCate: non_lastCategoryAllValue
        },
        () => this.search(1)
      )
      this.handleDropdownMenuChange(false)
    }
  }
  handleJump = (pagePath: PagePath, query: INullable<Recordable> = null) => {
    navigation(pagePath, query)
  }
  renderListTip = () => {
    const { list } = this.state
    if (list.length === 0) return null
    return (
      <View className="font-normal text-center yahei text-26px text-hex-666 leading-60px">
        暂无更多信息，看看别的内容吧~
      </View>
    )
  }
  renderFilterPanels() {
    const {
      selectedFilterKey,
      yearOptions,
      categoryOptions,
      areaOptions,
      lastAreaOptions,
      selectedAreaLastCate,
      selectedAreaFirstCate,
      selectedCategory,
      selectedYear
    } = this.state
    if (yearOptions.length <= 0 && categoryOptions.length <= 0 && areaOptions.length <= 0) {
      return null
    }
    return (
      <Sticky>
        {/* 下拉选择面板 */}
        <View catchMove>
          <DropdownMenu
            value={selectedFilterKey}
            onChange={this.handleDropdownMenuChange}
            className={clsx(
              styles["filter-dropdown"],
              "filter-dropdown",
              "myStyles-filter-dropdown"
            )}
          >
            {yearOptions && yearOptions.length > 0 ? (
              <DropdownMenu.Item title="招生年份">
                <View className="flex flex-col flex-1 overflow-hidden">
                  <View className={myStyles["dropdown-list-content"]}>
                    <View className="flex-1">
                      <ScrollView
                        scrollY
                        style={{
                          height: "100%"
                        }}
                      >
                        {yearOptions.map(l => (
                          <Cell
                            key={l.value}
                            title={l.text}
                            align="center"
                            clickable
                            onClick={() => this.handleClickYear(l)}
                            className={clsx(styles["filter-dropdown-cell"], {
                              [styles["checked"]]: l.value === selectedYear
                            })}
                          >
                            {l.value === selectedYear && (
                              <Success
                                color="#1A8CFF"
                                style={{
                                  fontSize: iconSize
                                }}
                              />
                            )}
                          </Cell>
                        ))}
                      </ScrollView>
                    </View>
                  </View>
                </View>
              </DropdownMenu.Item>
            ) : null}
            {areaOptions && areaOptions.length > 0 ? (
              <DropdownMenu.Item title="所在地区">
                <View className="flex flex-row flex-1 overflow-hidden">
                  <View className="flex-none overflow-auto w-280px bg-hex-f5f5f5">
                    <ScrollView
                      scrollY
                      style={{
                        height: "100%"
                      }}
                    >
                      {areaOptions.map(l => (
                        <View
                          key={l.value}
                          onClick={() => this.handleClickAreaFirstCate(l)}
                          className={clsx(myStyles["filter-dropdown-first-cate"], {
                            [myStyles["checked"]]: l.value === selectedAreaFirstCate
                          })}
                        >
                          {l.text}
                        </View>
                      ))}
                    </ScrollView>
                  </View>
                  <View className="flex-1 overflow-auto">
                    <ScrollView
                      scrollY
                      style={{
                        height: "100%"
                      }}
                    >
                      {lastAreaOptions.map(l => (
                        <Cell
                          key={l.value}
                          title={l.text}
                          align="center"
                          clickable
                          onClick={() => this.handleClickAreaLastCate(l)}
                          className={clsx(styles["filter-dropdown-cell"], {
                            [styles["checked"]]: l.value === selectedAreaLastCate
                          })}
                        >
                          {l.value === selectedAreaLastCate && (
                            <Success color="#1A8CFF" style={{ fontSize: iconSize }} />
                          )}
                        </Cell>
                      ))}
                    </ScrollView>
                  </View>
                </View>
              </DropdownMenu.Item>
            ) : null}
            {categoryOptions && categoryOptions.length > 0 ? (
              <DropdownMenu.Item title="培训项目">
                <View className="flex flex-col flex-1 overflow-hidden">
                  <View className={myStyles["dropdown-list-content"]}>
                    <View className="flex-1">
                      <ScrollView
                        scrollY
                        style={{
                          height: "100%"
                        }}
                      >
                        {categoryOptions.map(l => (
                          <Cell
                            key={l.value}
                            title={l.text}
                            align="center"
                            clickable
                            onClick={() => this.handleClickCategory(l)}
                            className={clsx(styles["filter-dropdown-cell"], {
                              [styles["checked"]]: l.value === selectedCategory
                            })}
                          >
                            {l.value === selectedCategory && (
                              <Success
                                color="#1A8CFF"
                                style={{
                                  fontSize: iconSize
                                }}
                              />
                            )}
                          </Cell>
                        ))}
                      </ScrollView>
                    </View>
                  </View>
                </View>
              </DropdownMenu.Item>
            ) : null}
          </DropdownMenu>
        </View>
      </Sticky>
    )
  }
  render() {
    const { keyword, list, showLoading, picture, navigationTitle } = this.state
    const listLen = list.length
    return (
      <GpContainer className="professional">
        <View className={styles["top-fixed"]}>
          <View className={myStyles["bg-wrap"]}>
            <View className={myStyles["banner-wrap"]}>
              <Image src={picture as string} mode="aspectFit" className={myStyles.image} />
            </View>
            <View className={myStyles["search-wrap"]}>
              <Search
                className={clsx("search-input-column", myStyles["search-input"])}
                shape="round"
                placeholder="请输入搜索关键词"
                value={keyword}
                onChange={this.handleKeywordChange}
                onSearch={() => this.search(1)}
                clearable={false}
              />
            </View>
          </View>
          {this.renderFilterPanels()}
        </View>
        {/* placeholoder */}
        {/* <View className="pt-396px"></View> */}
        {/* 列表内容 */}
        <View className="flex flex-col mt-12px px-30px bg-hex-ffffff py-26px">
          {list.length > 0 ? (
            list.map((l, index) => (
              <GpMustReadItem
                key={l.id}
                mustReadItem={l}
                className={clsx({
                  "mb-20px": index !== listLen - 1
                })}
              />
            ))
          ) : (
            <GpEmpty />
          )}
        </View>
        {showLoading ? (
          <GpScrollLoading />
        ) : (
          <React.Fragment>
            {this.renderListTip()}
            {/* 快捷导航 */}
            {this.renderJumpNavs()}
            {/* 当前位置 */}
            <GpCurrentPort />
          </React.Fragment>
        )}
        {/* 底部导航 */}
        <GpTabbar type={12} navigationTitle={navigationTitle} />
      </GpContainer>
    )
  }
}
export default ColumnDetail
